package com.basic.codetool;

import java.io.IOException;
import java.io.StringWriter;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;

import com.basic.common.FuncFile;

/**
 * 
 * 生成WEB相关文件 ， control文件， vm文件， 修改ViewFile文件
 *
 */
public class CreateWebFile {
	public static String foldName =null;
	public static String encode = "UTF-8";
	static {
		Velocity.addProperty(Velocity.ENCODING_DEFAULT, encode);
		Velocity.addProperty(Velocity.INPUT_ENCODING, encode);
		Velocity.addProperty(Velocity.OUTPUT_ENCODING, encode); 
		Velocity.addProperty(Velocity.FILE_RESOURCE_LOADER_PATH, CreateFile.class.getResource("").toString()
				.replaceAll("^file:/", ""));
		Velocity.init();
	}
	
	public static void main(String[] args) throws Exception {
		foldName = "E:/Work/Project/banyou/src/main/java/myweb";
		String[] files = new String[]{"ViewpointView"};
		for(String file : files){
			createFile(file);
		}
		System.out.println("OK");
	}
	
	private static void createFile(String fileName) throws Exception {
		
		
		//生成control
		Context context = new VelocityContext();
		context.put("filename", fileName); 
		context.put("filename_low", fileName.toLowerCase()); 
		StringWriter sw = new StringWriter();
		Velocity.mergeTemplate("WebControl.vm", encode, context, sw);
		if(!FuncFile.isExist( foldName+"/control/"+fileName+".java")){
			FuncFile.insertFile(foldName+"/control/"+fileName+".java", sw.toString());
		}
		
		
		//修改ViewFile
		String txt = FuncFile.readText(foldName+"/conf/ViewFile.java",encode);
		txt = txt.replaceAll("//newline", "String "+fileName.toLowerCase()+" = \""+fileName.toLowerCase()+".vm\";\r\n\t//newline");
		FuncFile.insertFile(foldName+"/conf/ViewFile.java", txt);
		
		if(!FuncFile.isExist(foldName+"/view/"+fileName.toLowerCase()+".vm")){
			//添加vm
			FuncFile.insertFile(foldName+"/view/"+fileName.toLowerCase()+".vm", "");
		}
	}
}
